package cn.turboinfo.fuyang.api.domain.share.usecase.shop;

import cn.turboinfo.fuyang.api.domain.common.service.division.DivisionService;
import cn.turboinfo.fuyang.api.domain.common.service.shop.HousekeepingShopService;
import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.domain.util.BeanHelper;
import cn.turboinfo.fuyang.api.entity.common.pojo.division.Division;
import cn.turboinfo.fuyang.api.entity.common.pojo.shop.HousekeepingShop;
import cn.turboinfo.fuyang.api.entity.share.fo.shop.ShareShopFO;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 门店详情
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class ShareViewShopUseCase extends AbstractUseCase<ShareViewShopUseCase.InputData, ShareViewShopUseCase.OutputData> {

    private final HousekeepingShopService housekeepingShopService;

    private final DivisionService divisionService;

    @Override
    protected OutputData doAction(InputData inputData) {

        Long companyId = inputData.getCompanyId();
        Long shopId = inputData.getShopId();
        HousekeepingShop shop = housekeepingShopService.getByIdEnsure(shopId);

        if (!shop.getCompanyId().equals(companyId)) {
            throw new RuntimeException("家政员不属于该企业");
        }

        Set<Long> divisionCodeSet = new HashSet<>();
        divisionCodeSet.add(shop.getProvinceCode());
        divisionCodeSet.add(shop.getCityCode());
        divisionCodeSet.add(shop.getAreaCode());

        Map<Long, Division> divisionMap = divisionService.findByIdCollection(divisionCodeSet)
                .stream()
                .collect(Collectors.toMap(Division::getId, o -> o));
        ShareShopFO.ShareShopFOBuilder builder = ShareShopFO.builder();
        BeanHelper.copyPropertiesToBuilder(builder, ShareShopFO.class, shop);

        return OutputData.builder()
                .shop(builder
                        .provinceName(divisionMap.get(shop.getProvinceCode()).getAreaName())
                        .cityName(divisionMap.get(shop.getCityCode()).getAreaName())
                        .areaName(divisionMap.get(shop.getAreaCode()).getAreaName())
                        .build())
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        @NotNull(message = "公司ID不能为空")
        @Positive
        private Long companyId;

        @NotNull(message = "门店编码不能为空")
        @Positive
        private Long shopId;
    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

        private ShareShopFO shop;

    }
}
